package examples;

import helpers.UrlHelper;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.DomainData;
import data.GoogleAdsenceData;
import data.GoogleAnalyticData;
import debugs.DomainDebug;

import services.UpdateDomain;
import models.DomainModel;

public class DomainEx extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		
		String domainName = (String) request.getParameter("domain");
		if (domainName == null || domainName.isEmpty()) {
			domainName = "www.websiteus.org";
		}
		if (!UrlHelper.checkDomain(domainName)) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		DomainData dData = new DomainData();
		DomainModel domain = dData.get(domainName);
		if (domain == null) {
			domain = new DomainModel();
			domain.setDomain(domainName);
		
			UpdateDomain updateDomain = new UpdateDomain(domain);
			domain = updateDomain.getDomain();
			
			check = updateDomain.getCheck();
			
			if (check.get("fDomain") != null || check.get("server") != null || check.get("siteinfo") != null) {
				
			} else {
				DomainData domainData = new DomainData();
				domainData.insert(domain);
				
				if (check.get("googleService") == null && !domain.getGoogleAnalyticId().isEmpty()) {
					GoogleAnalyticData analyticData = new GoogleAnalyticData();
					analyticData.add(domain.getGoogleAnalyticId(), updateDomain.getGoogleAnalyticSites());
				}
				
				if (check.get("googleService") == null && !domain.getGoogleAdsenseId().isEmpty()) {
					GoogleAdsenceData adsenceData = new GoogleAdsenceData();
					adsenceData.add(domain.getGoogleAdsenseId(), updateDomain.getGoogleAdsenceSites());
				}
				
				if (check.get("googleService") == null) {
					
				}
			}
		}
		
		request.setAttribute("domain", domain);
		request.setAttribute("check", check);
		
		try {
			request.getRequestDispatcher("/examples/domain-ex.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
